/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ui.helpers;

import core.ChangesObserver;
import core.Database;
import core.DatabaseTable;
import core.TableColumn;
import core.XmlParser;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.log4j.Logger;
import ui.ApplicationWindow;
import ui.DbVersioning;

/**
 *
 * @author Sakis Vtdk <sakis.vtdk@gmail.com>
 */
public class LoadListener implements ActionListener
{

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		//get the filechooser
		JFileChooser fileChooser = ApplicationWindow.getApplicationWindow().getFileChooser();

		//set the default path
		fileChooser.setCurrentDirectory(new File(DbVersioning.DEFAULT_DATA_FOLDER));
		
		//only file choosing
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

		//only .dbv files
		FileFilter filter = new FileNameExtensionFilter("DB Versions files", "dbv");
		fileChooser.setFileFilter(filter);
		
		//get the user's selection
		int choice = fileChooser.showOpenDialog(null);

		if(choice == JFileChooser.APPROVE_OPTION)
		{
			File file = fileChooser.getSelectedFile();

			try
			{
				ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));

				Database db = Database.getDatabase(inputStream);
				
				//get the path and the filename ////// are these needed?
				//String fileName = file.getName();
				//String path = file.getPath().substring(0, file.getPath().indexOf(fileName));

				inputStream.close();

				//load the xml file for this database
				loadXml();

				//add observers in everything in the database
				addObservers(db);

				//take a snapshot of the database
				//Database.takeSnapshot();
				log.trace("Db loaded: "+db.getDatabaseName());
				ApplicationWindow.getApplicationWindow().refreshItems();
			}
			catch(IOException exc)
			{
				JOptionPane.showMessageDialog(null, "There was an error when opening a file", "Error", JOptionPane.ERROR_MESSAGE);
				log.fatal("The following error occured when trying to open the file: "+ exc.getMessage());
			}
			catch(ClassNotFoundException exc)
			{
				JOptionPane.showMessageDialog(null, "There was an error when reading from file", "Error", JOptionPane.ERROR_MESSAGE);
				log.fatal("The following error occured when trying to read from file: "+ exc.getMessage());
			}
			catch(Exception exc)
			{
				JOptionPane.showMessageDialog(null, "There was an error when loading the file", "Error", JOptionPane.ERROR_MESSAGE);
				log.fatal("The following error occured when trying to open the file: "+ exc.getMessage());
			}

		}
	}

	/**
	 * Adds observers to the database object, the tables contained, 
	 * and the columns within the tables if they do not already have one
	 * @param db 
	 */
	private void addObservers(Database db)
	{
		if(db.countObservers() == 0) { db.addObserver(new ChangesObserver()); }

		for(DatabaseTable dbTable : db.getTables())
		{
			if(dbTable.countObservers() == 0) { dbTable.addObserver(new ChangesObserver()); }

			for(TableColumn tblColumn: dbTable.getColumns())
			{
				if(tblColumn.countObservers() == 0) { tblColumn.addObserver(new ChangesObserver()); }
			}
		}
		
	}

	private void loadXml()
	{
		//get the xmlParser object
		XmlParser xmlParser = XmlParser.getXmlParser();

		//load the .xml file
		xmlParser.loadXmlFile(DbVersioning.DEFAULT_CHANGES_FOLDER + File.separator + Database.getDatabase().getDatabaseName() +".xml");

		//parse the changes in that file to the ChangesLogger
		xmlParser.parseXmlChanges();
	}

	private static Logger log = Logger.getLogger(LoadListener.class);
}
